package com.tenglong.teacher.ui.answerq.relate;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.BaseFragment;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.cuotibao.zhuoxiao.basics.utils.recyview.DividerSpaceItemDecoration;
import com.netease.nim.uikit.business.session.constant.Extras;
import com.netease.nim.uikit.impl.customization.DefaultP2PSessionCustomization;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.AnswerInfo;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.DateInfo;
import com.tenglong.teacher.data.resultInfo.RelateHeaderData;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.port.MainFragmentRubsh;
import com.tenglong.teacher.ui.adapter.DateInfoAdapter;
import com.tenglong.teacher.ui.adapter.RelateAnswerAdaper;
import com.tenglong.teacher.ui.adapter.RelateScourseAdapter;
import com.tenglong.teacher.ui.answerq.chat.P2PChatActivity;
import com.tenglong.teacher.ui.common.view.SelecSlideView;
import com.tenglong.teacher.ui.utils.NimUtils;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class RelateAnswerFragment extends BaseFragment implements View.OnClickListener, MainFragmentRubsh, RelateAnswerAdaper.RelateAnswerListener, OnRefreshListener {


    private TextView mGrade;
    private TextView mClassName;
    private TextView mDate;
    private boolean isShowWindow = false;
    private View rl;
    private SelecSlideView mDateWindow;
    private List<RelateHeaderData.ScourseName> scourseNames;
    private SelecSlideView scourseView;
    private ArrayList<RelateHeaderData.ScourseName> gradeNames;
    private RelateScourseAdapter gradeAdapter;
    private RelateScourseAdapter scourseAdapter;
    private SelecSlideView gradeView;
    private int mLastScoursePosition = 0;
    private int mLastGradePosition = 0;
    private int mLastDatePosition = 0;
    private DateInfoAdapter dateAdapter;
    private RecyclerView recyclerView;
    private List<AnswerInfo> infos;
    private RelateAnswerAdaper mAdapter;

    private String courseId = "-1";
    private String gradeid = "-1";
    private int idate = 0;
    private View noData;
    private int mClickPosition = 0;
    private SmartRefreshLayout mSmartRefreshLayout;

    public RelateAnswerFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_relate_answer, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initDateSelector();
        initScourseSelector();
        initGredesSelector();
        initRecycle();
        setAdapter();
        setListeners(view);
        requestHeaderData();
        requestData(courseId, gradeid, idate);
        isShowWindow = true;
    }

    private void setAdapter() {
        infos = new ArrayList<>();
        mAdapter = new RelateAnswerAdaper(infos);
        recyclerView.setAdapter(mAdapter);
    }

    private void initRecycle() {
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new DividerSpaceItemDecoration(Utils.dip2px(mContext, 15)));
    }


    private void initDateSelector() {
        dateAdapter = new DateInfoAdapter();
        mDateWindow = new SelecSlideView(mContext, new GridLayoutManager(mContext, 3), dateAdapter.setOnDateItemListener(new DateInfoAdapter.DateItemListener() {
            @Override
            public void onDateItemListener(DateInfo info, int position) {
                if (position == -1) return;
                info.isSele = true;
                dateAdapter.notifyItemChanged(position);
                if (mLastDatePosition != position) {
                    dateAdapter.getItemById(mLastDatePosition).isSele = false;
                    dateAdapter.notifyItemChanged(mLastDatePosition);
                }
                mLastDatePosition = position;
                mDate.setText(info.date);
                mDateWindow.dismiss();
                idate = info.stype;
                requestData(courseId, gradeid, idate);
            }
        }));
    }

    private void initGredesSelector() {
        gradeNames = new ArrayList<>();
        gradeAdapter = new RelateScourseAdapter(gradeNames);
        gradeView = new SelecSlideView(mContext, new GridLayoutManager(mContext, 3), gradeAdapter.setRelateScourseListener(new RelateScourseAdapter.RelateScourseListener() {
            @Override
            public void onRelateScourseListener(RelateHeaderData.ScourseName info, int position) {
                if (position == -1) return;
                info.isSele = true;
                gradeAdapter.notifyItemChanged(position);
                if (mLastGradePosition != position) {
                    gradeNames.get(mLastGradePosition).isSele = false;
                    gradeAdapter.notifyItemChanged(mLastGradePosition);
                }
                mLastGradePosition = position;
                if (gradeNames.size() == 1) {
                    mGrade.setText("年级");
                } else {
                    mGrade.setText(info.label.equals("全部") || info.label.equals("其他") ? "年级" : info.label);
                }
                gradeView.dismiss();
                gradeid = info.value;
                requestData(courseId, gradeid, idate);
            }
        }));
    }

    private void initScourseSelector() {
        scourseNames = new ArrayList<>();
        scourseAdapter = new RelateScourseAdapter(scourseNames);
        scourseView = new SelecSlideView(mContext, new GridLayoutManager(mContext, 3), scourseAdapter.setRelateScourseListener(new RelateScourseAdapter.RelateScourseListener() {
            @Override
            public void onRelateScourseListener(RelateHeaderData.ScourseName info, int position) {
                if (position == -1) return;
                info.isSele = true;
                scourseAdapter.notifyItemChanged(position);
                if (mLastScoursePosition != position) {
                    scourseNames.get(mLastScoursePosition).isSele = false;
                    scourseAdapter.notifyItemChanged(mLastScoursePosition);
                }
                mLastScoursePosition = position;
                if (scourseNames.size() == 1) {
                    mClassName.setText("科目");
                } else {
                    mClassName.setText(info.name.equals("全部") || info.name.equals("其他") ? "科目" : info.name);
                }
                scourseView.dismiss();
                courseId = info.id;
                requestData(courseId, gradeid, idate);
            }
        }));
    }

    private void requestHeaderData() {
        if (scourseNames.size() != 0 && gradeNames.size() != 0 && !DataState.getInstance().isCorrelationAnswerIsClassNumChange())
            return;
        CreateRequestEntity.getWebService().getCourseAndGradeByUserId().enqueue(new Callback<BaseResult<RelateHeaderData>>() {
            @Override
            public void onResponse(Call<BaseResult<RelateHeaderData>> call, Response<BaseResult<RelateHeaderData>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    scourseNames.clear();
                    gradeNames.clear();
                    if (response.body().data.scourseName != null) {
                        if (response.body().data.scourseName.size() == 1) {
                            RelateHeaderData.ScourseName info = response.body().data.scourseName.get(0);
                            info.isSele = true;
                        } else {
                            for (RelateHeaderData.ScourseName scourseName : response.body().data.scourseName) {
                                if (scourseName.name.equals("全部") || scourseName.name.equals("其他")) {
                                    scourseName.isSele = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (response.body().data.gredesName != null) {
                        if (response.body().data.gredesName.size() == 1) {
                            response.body().data.gredesName.get(0).isSele = true;
                        } else {
                            for (RelateHeaderData.ScourseName scourseName : response.body().data.gredesName) {
                                if (scourseName.label.equals("全部") || scourseName.label.equals("其他")) {
                                    scourseName.isSele = true;
                                    break;
                                }
                            }
                        }
                    }
                    DataState.getInstance().setCorrelationAnswerIsClassNumChange(false);
                    scourseNames.addAll(response.body().data.scourseName);
                    gradeNames.addAll(response.body().data.gredesName);
                    gradeAdapter.notifyDataSetChanged();
                    scourseAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<RelateHeaderData>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
            }
        });
    }

    private void requestData(String courseId, String gradeid, int idate) {
        if (isFirstDownLoad) {
            showProgressDialog("数据加载中...");
            isFirstDownLoad = false;
        }
        CreateRequestEntity.getWebService().getRelateAnswerList(courseId, idate, gradeid).enqueue(new Callback<BaseResult<List<AnswerInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<AnswerInfo>>> call, Response<BaseResult<List<AnswerInfo>>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    infos.clear();
                    infos.addAll(response.body().data);
                    mAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
                noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                mSmartRefreshLayout.finishRefresh(true);
                dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseResult<List<AnswerInfo>>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                mSmartRefreshLayout.finishRefresh(false);
                dismissProgressDialog();
            }
        });
    }

    private void setListeners(View view) {
        view.findViewById(R.id.rl_search).setOnClickListener(this);
        mDate.setOnClickListener(this);
        mClassName.setOnClickListener(this);
        mGrade.setOnClickListener(this);
        mAdapter.setRelateAnswerListener(this);
        mSmartRefreshLayout.setEnableLoadMore(false);
        mSmartRefreshLayout.setOnRefreshListener(this);
    }

    private void initView(View view) {
        mGrade = view.findViewById(R.id.btn_grade);
        mClassName = view.findViewById(R.id.btn_className);
        mDate = view.findViewById(R.id.btn_date);
        rl = view.findViewById(R.id.rl);
        recyclerView = view.findViewById(R.id.recyclerView);
        noData = view.findViewById(R.id.noData);
        mSmartRefreshLayout = view.findViewById(R.id.smartRefreshLayout);
        ClassicsHeader headerView = new ClassicsHeader(getContext());
        ClassicsFooter footView = new ClassicsFooter(getContext());
        headerView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        footView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        mSmartRefreshLayout.setRefreshHeader(headerView);
        mSmartRefreshLayout.setRefreshFooter(footView);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_search:
                break;
            case R.id.btn_date:
                if ((scourseNames != null && scourseNames.size() > 0) || (gradeNames != null && gradeNames.size() > 0)) {
                    showSlideView(mDateWindow);
                } else {
                    ToastUtils.showCenterToast("请先去创建班级");
                }
                break;
            case R.id.btn_className:
                if (scourseNames != null && scourseNames.size() > 0) {
                    showSlideView(scourseView);
                } else {
                    ToastUtils.showCenterToast("请先去创建班级");
                }
                break;
            case R.id.btn_grade:
                if (gradeNames != null && gradeNames.size() > 0) {
                    showSlideView(gradeView);
                } else {
                    ToastUtils.showCenterToast("请先去创建班级");
                }
                break;
        }
    }


    private void showSlideView(SelecSlideView pop) {
        pop.showAsDropDown(rl);
    }

    @Override
    public void refresh() {
        if (isAdded() && isShowWindow) {
            requestHeaderData();
            requestData(courseId, gradeid, idate);
        }
    }

    @Override
    public void onRelateAnswerListener(final AnswerInfo info, final int position) {
        if (position == -1) return;
        mClickPosition = position;
        Intent intent = new Intent();
        intent.setClass(mContext, P2PChatActivity.class);
        intent.putExtra(Extras.EXTRA_ACCOUNT, info.studentid);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, new DefaultP2PSessionCustomization());
        intent.putExtra(Extras.KEY_SE_ID, info.id);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Extras.KEY_SELECT_STATE, info.collect);
        intent.putExtra(Extras.KEY_P2P_TITLE, info.studentname);
        intent.putExtra(Extras.KEY_INPUT_BOX_STATE, false);
        intent.putExtra(Extras.EXTRA_ANCHOR, info.questioning == null ? null : NimUtils.createQuestionSessionIdUtiMesssage(info, NimUtils.ANSWER_QESTION_TYPE, info.id));
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_P2P_CHAT_ACTIVITY);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_P2P_CHAT_ACTIVITY:
                    if (data != null) {
                        collectOrCancle(data);
                    }
                    break;
            }
        }
    }

    private void collectOrCancle(Intent data) {
        AnswerInfo info = infos.get(mClickPosition);
        info.collect = data.getBooleanExtra(Extras.KEY_SELECT_STATE, false);
        info.favorite = info.collect ? info.favorite += 1 : (info.favorite == 0 ? 0 : (info.favorite -= 1));
        mAdapter.notifyItemChanged(mClickPosition);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        requestHeaderData();
        requestData(courseId, gradeid, idate);
    }
}
